package cc.shacocloud.mirage.restful;

import cc.shacocloud.mirage.core.ApplicationContext;
import cc.shacocloud.mirage.restful.bind.annotation.WebFilter;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 基于 mirage Bean 的路由过滤器映射
 */
public class MirageRouterFilterMappingHandler extends VertxRouterFilterMappingHandler {
    
    @Override
    public void init() {
        ApplicationContext applicationContext = obtainApplicationContext();
        if (Objects.nonNull(applicationContext)) {
            
            // 绑定过滤器
            String[] beanNames = applicationContext.getBeanNamesForAnnotation(WebFilter.class);
            
            List<FilterMappingInfo> filters = new ArrayList<>();
            for (String beanName : beanNames) {
                Class<?> beanType = applicationContext.getBeanType(beanName);
                
                if (Filter.class.isAssignableFrom(beanType)) {
                    WebFilter webFilter = applicationContext.findAnnotationOnBean(beanName, WebFilter.class);
                    if (webFilter == null) continue;
                    
                    filters.add(
                            FilterMappingInfo.builder()
                                    .filterName(webFilter.filterName())
                                    .includePatterns(webFilter.includePatterns())
                                    .excludePatterns(webFilter.excludePatterns())
                                    .filter((Filter) applicationContext.getBean(beanType))
                                    .order(webFilter.order())
                                    .build()
                    );
                }
            }
            
            // 添加过滤器
            addFilter(filters);
        }
    }
    
}
